package com.helloandroid.models

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.*
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.*
import com.helloandroid.tools.*
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.vo.*
import kotlinx.coroutines.launch
import org.json.JSONObject

class ZhuanViewModel : ViewModel(){

    fun getInfo(callback:(Boolean,TaskInfo?)->Unit){

        val info = AppCache.copyTaskInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
            val url = "task/info?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseTaskInfo)

            if(parseResult.err == 0){
                val taskInfo = parseResult.obj as TaskInfo
                AppCache.taskInfo = taskInfo
                callback(true,AppCache.copyTaskInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }

//    fun sign(){
//
//        if (!NetWorkUtil.networkConnected()){
//            AppUtil.toast("请打开网络!")
//            return
//        }
//
//        viewModelScope.launch {
//            val url = "user/signup?user_id=${MyApplication.user!!.user_id}"
//            val jsonObj = JSONObject(asyncHttpReq(url))
//            val parseResult = jsonObj.process(JSONObject::parseSignResponse)
//            if(parseResult.err == 0){
//                val signResponse = parseResult.obj as SignResponse
//                AppUtil.toast("恭喜,领取${signResponse.added}金币奖励!")
//                MyApplication.setCoin(signResponse.total)
//                MyApplication.updateSignInfo(signResponse.signTimeMs,signResponse.signedCount)
//                signState.value = 1
//            }else{
//                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
//                AppUtil.toast("对不起,签到失败!")
//            }
//        }
//    }
}
